package org.ala.shopping_test.shopping_center.repository.order.router;

import java.util.List;
import java.util.Map;

import org.ala.shopping_test.shopping_center.repository.order.entity.ShoppingOrderDO;
import org.ala.shopping_test.shopping_center.repository.shard_key.ShoppingOrderShardKey;
import org.ala.shopping_test.shopping_center.repository.shard_key.ShoppingOrderShardKeyRouter;
import org.ala.tiktools.sharddb.mybatis.router.IShardRouter;
import org.ala.tiktools.sharddb.mybatis.router.ShardInfo;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.IShardKeyConverter;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.IShardKeyRouter;
import org.ala.tiktools.sharddb.mybatis.router.shard_key_router.ShardKeyRouteWorker;

/**
 *	分库分表路由器 (shopping_order)
 *  订单总表
 *
 *	@author 骆毅 (ala)
 *	@date 2025-03-19 15:17:51
 */
public class ShoppingOrderDOListRouter implements IShardRouter<List<ShoppingOrderDO>> {
    /**
     *  分片建路由器
     */
    protected IShardKeyRouter<ShoppingOrderShardKey> router = new ShoppingOrderShardKeyRouter();
    /**
     *  分片建转换器
     */
    protected IShardKeyConverter<ShoppingOrderDO, ShoppingOrderShardKey> converter = new IShardKeyConverter<ShoppingOrderDO, ShoppingOrderShardKey>() {
        @Override
        public ShoppingOrderShardKey convert(ShoppingOrderDO d) {
            return ShoppingOrderShardKey.build()
                    .id(d.getId())
                    .db(d.getShardDB())
                    .dbs(d.getShardDBIn())
                    .timestamp(d.getCreateTime() != null ? d.getCreateTime() : -1);
        }

        @Override
        public ShoppingOrderDO deConvert(ShoppingOrderDO d, ShoppingOrderShardKey k) {
            return d.copy()
                    .id(k.getId())
                    .shardDB(k.getDb())
                    .shardDBIn(k.getDbs())
                    .createTime(k.getTimestamp() > 0 ? k.getTimestamp() : null);
        }
    };


    /**
     * 分库分表
     */
    @Override
    public Map<ShardInfo, List<ShoppingOrderDO>> route(List<ShoppingOrderDO> d) {
        return ShardKeyRouteWorker.instance().route(d, router, converter);
    }
}